﻿using UnityEngine;
namespace FrameWorkSong
{

    public abstract class Singleton<T>: MonoBehaviourSimplify where T:Singleton<T>
    {
        protected static T mInstance=null;
        public static T Instance
        {
            get
            {
                if (mInstance == null)
                {
                    mInstance = FindObjectOfType<T>();
                    if (mInstance==null)
                    {
                        var instanceName = typeof(T).Name;
                        var instanceObj = GameObject.Find(instanceName);
                        if (!instanceObj)
                        {
                            instanceObj= new GameObject(instanceName);
                        }
                        mInstance = instanceObj.AddComponent<T>();
                        //转换场景不会被删除
                        DontDestroyOnLoad(instanceObj);
                        Debug.LogFormat("创建新的{0}单例实体", instanceName);
                    }
                    else
                    {
                        Debug.LogFormat("已经有单例实体");
                    }
                }
                return mInstance;
            }
        }
        protected virtual void onDestroy()
        {
            mInstance = null;
        }
    }
}